package com.wuhao.jdqlib.tts

import android.content.Context
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import com.coder.vincent.smart_toast.SmartToast
import com.wuhao.jdqlib.utils.LogUtil
import java.util.Locale

/**
 * Created: Lpz
 * Date: 2024/12/11
 * Description:
 */
class SystemTTSRepository(private val context: Context) : UtteranceProgressListener(), TTS,
    TextToSpeech.OnUtteranceCompletedListener {
    private var isSuccess = true
    private val tts: TextToSpeech by lazy {
        TextToSpeech(context) { status ->
            if (status == TextToSpeech.SUCCESS) {
                val result: Int = tts.setLanguage(Locale.CHINA)
                tts.setPitch(0.9f) // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
                tts.setSpeechRate(2.0f)
                tts.setOnUtteranceProgressListener(this@SystemTTSRepository)

                //                    textToSpeech.setOnUtteranceProgressListener(SystemTTS.this);
                if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED
                ) {
                    //系统不支持中文播报
                    isSuccess = false
                }
            }
        }
    }

    fun playText(playText: String) {
        //替换发音
        val msg = playText.replace("记弹器", "记蛋器")
        playText(msg, "default")
    }

    override fun playText(playText: String, code: String) {
        if (!isSuccess) {
            SmartToast.emotion().warning("系统不支持中文播报")
            return
        }
        tts.speak(playText, TextToSpeech.QUEUE_ADD, null, code)
    }

    override fun stopSpeak() {
        tts.stop()
    }

    // 释放资源
    fun onDestroy() {
        tts.shutdown()
    }

    /**
     * 播报完成回调
     *
     * @param utteranceId
     */
    override fun onUtteranceCompleted(utteranceId: String) {
        LogUtil.error("---utteranceId $utteranceId")
    }

    override fun onStart(utteranceId: String) {
        LogUtil.error("---onStart $utteranceId")

        //  MainActivity.mRecorder.stopRecording();
    }

    override fun onDone(utteranceId: String) {
        LogUtil.error("---onDone $utteranceId")

        //  MainActivity.mRecorder.startRecorder();
    }

    override fun onError(utteranceId: String) {
        LogUtil.error("---onError $utteranceId")
    }
}